package marcus.age.impl;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import marcus.age.AgeFormatter;
import marcus.jpa.entities.Contact;

import org.apache.commons.lang3.time.DateUtils;
import org.joda.time.Period;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;

public class LongAgeFormatter implements AgeFormatter {

	public String format(Contact contact, Period period, Date date) {
		Date today = DateUtils.truncate(new Date(), Calendar.DATE);

		SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy");
		
		String willBe = null;
		String dateString = " on " + sdf.format(date);
		if (today.equals(date)){
			willBe = " is ";
			dateString="today";
		}
		else if (date.before(today)){
			willBe = " was ";
		}
		else {
			willBe = " will be ";
		}
		
		if (period == null){
			return contact.getId().getName() +" wasn't born " + dateString;
		}
		PeriodFormatter formatter = new PeriodFormatterBuilder()
		.appendLiteral(contact.getId().getName() + willBe )
		.appendYears()
		.appendSuffix(" year ", " years ")
        .appendSeparator(" and ")
        .appendMonths()
        .appendSuffix(" month ", " months ")
        .appendSeparator(" and ")
        .appendDays()
        .appendSuffix(" day ", " days ")
        .appendLiteral("old " + dateString + ".")
        .toFormatter();
		
		return formatter.print(period);
	}

}
